<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-weight: 16">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>类别管理</el-breadcrumb-item>
      <el-breadcrumb-item v-for="item in history" :key="item.id"><span v-text="item.name"></span>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <div style="margin-bottom: 20px">
      <el-button type="primary" size="medium"
                 @click="$router.push('/sys-admin/product/category/add-new')">添加类别
      </el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
      <el-table-column prop="icon" label="图标" width="180" header-align="center">
        <template slot-scope="scope">
          <el-avatar :size="30" :src="scope.row.icon" fit="contain"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="180" header-align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="keywords" label="关键词列表" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="100" align="center"></el-table-column>
      <el-form-item label="是否启用" prop="enable">
        <el-switch
            v-model="enable"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ccc">
        </el-switch>
      </el-form-item>
      <el-form-item label="显示在导航栏" prop="enable">
        <el-switch
            v-model="isDisplay"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ccc">
        </el-switch>
      </el-form-item>
      <el-table-column label="子级类别" width="100" align="center">
        <template slot-scope="scope">
          <el-button size="mini" :disabled="scope.row.isParent == 0"
                     @click=showSubCategoryList(scope.row)>查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" circle
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" circle
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 返回上层 -->
    <div v-if="currentParentId!=0" style="margin-top: 10px; text-align: right">
      <el-button size="small" @click="goBack()">返回</el-button>
    </div>

    <!-- 修改类别的弹出表单Dialog -->
    <el-dialog title="修改类别" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="图标" prop="icon">
          <el-input v-model="editForm.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="关键词列表" prop="keywords">
          <el-input v-model="editForm.keywords" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 浏览历史，此数据主要用于返回功能
      history: [],
      // 修改对话框是否显示
      dialogFormVisible: false,
      // 当前类别列表的父级类别ID,用于显示下级列表
      currentParentId: 0,
      // 编辑表单
      editForm: {
        id: '',
        icon: '',
        name: '',
        keywords: '',
        sort: ''
      },
      // 表单项的验证规则
      rules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入排序序号', trigger: 'blur'},
          {pattern: /^(\d{1}|[1-9]{1}[0-9]?)$/, message: '排序序号必须是0~99之间的数字', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    // 返回按钮
    goBack() {
      let parentCategory = this.history[this.history.length - 1];
      this.currentParentId = parentCategory.parentId;
      this.loadCategoryList();
      // pop方法的作用是使当前数组删掉最后一个元素，倒数第二个元素变成倒数第一个元素，并且长度-1
      this.history.pop();
    },
    // 查看按钮-根据id查询类别，同时将父级类别的深度记录到history数组中，以便实现返回
    showSubCategoryList(category) {
      // 每点一次查看就把这个类别保存进数组里，从1依次排列
      this.history[category.depth - 1] = category;

      this.currentParentId = category.id;
      this.loadCategoryList();
    },
    // 打开编辑类别详情对话框-【根据ID查询类别详情】
    openEditDialog(category) {
      let url = 'http://localhost:9180/categories/' + category.id;
      console.log('url=' + url);
      let localJwt = localStorage.getItem('localJwt');
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          console.log('jsonResult.data: ', jsonResult.data);
          this.dialogFormVisible = true;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadCategoryList();
            }
          });
        }
      })
    },
    // 提交编辑表单-【根据ID修改类别详情】
    submitEditForm() {
      let url = 'http://localhost:9180/categories/' + this.editForm.id + '/update';
      console.log('url' + url);

      let formData = this.qs.stringify(this.editForm);

      let localJwt = localStorage.getItem('localJwt');
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '修改类别成功！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadCategoryList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadCategoryList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
            }
          });
        }
      })
    },
    // 删除按钮-根据ID删除类别
    openDeleteConfirm(category) {
      let url = 'http://localhost:9180/categories/' + category.id + '/delete';
      let localJwt = localStorage.getItem('localJwt');
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url, localJwt).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除类别成功！',
            type: 'success'
          });
          this.loadCategoryList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAlbumList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    // 加载类别列表
    loadCategoryList() {
      let url = 'http://localhost:9180/categories/' + this.currentParentId + '/list';
      let localJwt = localStorage.getItem('localJwt');
      console.log('Jwt=' + localJwt);
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              // this.$message({
              //   type: 'info',
              //   message: `action: ${ action }`
              // });
            }
          });
        }
      })
    }
  },
  mounted() {
    this.loadCategoryList();
  }
}
</script>
